<template>
    <div class="aliyun-oss-config">
        <div class="card-wrap mb10 animate-on-enter">
            <a-space wrap>
                <a-button :icon="h(ReloadOutlined)" @click="onRefresh" :loading="loading">
                    刷新
                </a-button>
            </a-space>
        </div>

        <div class="card-wrap mb10 animate-on-enter animate-delay-1">
            <a-alert :message="formState.description" type="info" show-icon />
            <div class="mt10">
                <a-typography-text type="secondary">
                    需要帮助？请参考：
                    <a href="https://help.aliyun.com/zh/ram/product-overview/what-is-sts?spm=a2c4g.11186623.help-menu-28625.d_0_0_1.38b0595c6QRNqr&scm=20140722.H_28756._.OR_help-T_cn~zh-V_1"
                        target="_blank">
                        阿里云STS服务文档
                    </a>
                </a-typography-text>
            </div>
        </div>

        <div class="card-wrap animate-on-enter animate-delay-2">
            <a-spin :spinning="loading">
                <a-form ref="formRef" :model="formState" :label-col="{ span: 4 }" :wrapper-col="{ span: 16 }"
                    :rules="rules" @finish="onSubmit">
                    <a-form-item label="AccessKey ID" :name="['value', 'accessKeyId']">
                        <a-input v-model:value="formState.value.accessKeyId" placeholder="请输入阿里云AccessKey ID" />
                    </a-form-item>

                    <a-form-item label="AccessKey Secret" :name="['value', 'accessKeySecret']">
                        <a-input v-model:value="formState.value.accessKeySecret" placeholder="请输入阿里云AccessKey Secret" />
                    </a-form-item>

                    <a-form-item label="regionId" :name="['value', 'regionId']">
                        <a-input v-model:value="formState.value.regionId" placeholder="请输入地域ID，如：cn-hangzhou" />
                    </a-form-item>

                    <a-form-item label="RoleArn" :name="['value', 'roleArn']">
                        <a-input v-model:value="formState.value.roleArn" placeholder="请输入RAM角色ARN" />
                    </a-form-item>

                    <a-form-item label="Bucket" :name="['value', 'bucket']">
                        <a-input v-model:value="formState.value.bucket" placeholder="请输入Bucket名称" />
                    </a-form-item>

                    <a-form-item :wrapper-col="{ offset: 4, span: 16 }">
                        <a-button type="primary" :icon="h(SaveOutlined)" html-type="submit" :loading="saveLoading">
                            保存配置
                        </a-button>
                    </a-form-item>
                </a-form>
            </a-spin>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, h } from 'vue'
import { message } from 'ant-design-vue'
import { SaveOutlined, ReloadOutlined } from '@ant-design/icons-vue'
import { baseAPI } from '@/api/api.js'

// 响应式数据
const formRef = ref()
const loading = ref(false)
const saveLoading = ref(false)

// 表单数据
const formState = reactive({
    id: '',
    name: '阿里云OSS配置',
    key: 'aliyun_oss',
    value: {
        accessKeyId: '',
        accessKeySecret: '',
        regionId: '',
        roleArn: '',
        bucket: ''
    },
    description: '阿里云对象存储OSS基础配置信息'
})

// 表单验证规则
const rules = {
    value: {
        accessKeyId: [
            { required: true, message: '请输入AccessKey ID', trigger: 'blur' }
        ],
        accessKeySecret: [
            { required: true, message: '请输入AccessKey Secret', trigger: 'blur' }
        ],
        regionId: [
            { required: true, message: '请输入地域ID', trigger: 'blur' }
        ],
        roleArn: [
            { required: true, message: '请输入角色ARN', trigger: 'blur' }
        ],
        bucket: [
            { required: true, message: '请输入bucket', trigger: 'blur' }
        ]
    }
}

// 方法
function loadConfig() {
    loading.value = true

    baseAPI.get('PlatformConfig/getPlatformConfig', {
        key: 'aliyun_oss'
    })
        .then(function (response) {
            if (response.code === 200 && response.result) {
                // 如果有配置数据，则填充表单
                const config = response.result

                // 处理value，确保它是一个对象
                let configValue = config.value || {}
                if (typeof configValue === 'string') {
                    try {
                        configValue = JSON.parse(configValue)
                    } catch (e) {
                        console.error('解析value失败:', e)
                        configValue = {}
                    }
                }

                Object.assign(formState, {
                    id: config.id || '',
                    name: config.name || '阿里云OSS配置',
                    key: config.key || 'aliyun_oss',
                    value: {
                        accessKeyId: configValue.accessKeyId || '',
                        accessKeySecret: configValue.accessKeySecret || '',
                        regionId: configValue.regionId || '',
                        roleArn: configValue.roleArn || '',
                        bucket: configValue.bucket || ''
                    },
                    description: config.description || '阿里云对象存储OSS基础配置信息'
                })
            }
        })
        .catch(function (error) {
            console.error('加载配置失败:', error)
            message.error('加载配置失败')
        })
        .finally(function () {
            loading.value = false
        })
}

function onSubmit(values) {
    saveLoading.value = true

    const submitData = {
        name: formState.name,
        key: formState.key,
        value: values.value
    }

    baseAPI.post('PlatformConfig/saveConfig', submitData)
        .then(function (response) {
            if (response.code === 200) {
                message.success('保存成功')
                // 重新加载配置
                loadConfig()
            } else {
                message.error(response.message || '保存失败')
            }
        })
        .catch(function (error) {
            console.error('保存失败:', error)
            message.error('保存失败')
        })
        .finally(function () {
            saveLoading.value = false
        })
}


const onRefresh = () => {
    loadConfig()
}

// 生命周期
onMounted(() => {
    loadConfig()
})
</script>

<style scoped>
.aliyun-oss-config {
    .card-wrap {
        background: #fff;
        border-radius: 8px;
        padding: 24px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

        h3 {
            margin-bottom: 16px;
            color: #333;
            font-weight: 600;
        }
    }

    .mb10 {
        margin-bottom: 16px;
    }

    .mt10 {
        margin-top: 16px;
    }

    .animate-on-enter {
        animation: fadeInUp 0.6s ease-out;
    }

    .animate-delay-1 {
        animation-delay: 0.1s;
    }

    .animate-delay-2 {
        animation-delay: 0.2s;
    }

    @keyframes fadeInUp {
        from {
            opacity: 0;
            transform: translateY(20px);
        }

        to {
            opacity: 1;
            transform: translateY(0);
        }
    }
}
</style>